using Microsoft.AspNetCore.SignalR;
using SumerCoreDevOps.ControlApi.Hubs;
using SumerCoreDevOps.Infrastructure.Realtime;

namespace SumerCoreDevOps.ControlApi.Services;

/// <summary>
/// SignalR实时通知服务实现
/// </summary>
public class SignalRNotificationService : IRealtimeNotificationService
{
    private readonly IHubContext<DevOpsHub> _hubContext;
    private readonly ILogger<SignalRNotificationService> _logger;

    public SignalRNotificationService(
        IHubContext<DevOpsHub> hubContext,
        ILogger<SignalRNotificationService> logger)
    {
        _hubContext = hubContext;
        _logger = logger;
    }

    public async Task PushTaskLogAsync(long taskId, long pipelineInstanceId, string logLevel, string logContent)
    {
        try
        {
            // 推送到订阅该任务日志的客户端
            var taskLogsGroup = $"task-logs-{taskId}";
            await _hubContext.Clients.Group(taskLogsGroup).SendAsync("ReceiveTaskLog", new
            {
                taskId,
                logLevel,
                logContent,
                timestamp = DateTime.UtcNow
            });

            // 推送到订阅整个流水线实例的客户端
            var pipelineGroup = $"pipeline-instance-{pipelineInstanceId}";
            await _hubContext.Clients.Group(pipelineGroup).SendAsync("ReceiveTaskLog", new
            {
                taskId,
                pipelineInstanceId,
                logLevel,
                logContent,
                timestamp = DateTime.UtcNow
            });

            _logger.LogTrace("已推送任务日志到SignalR: TaskId={TaskId}", taskId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "推送任务日志到SignalR失败: TaskId={TaskId}", taskId);
        }
    }

    public async Task PushTaskStatusAsync(long taskId, long pipelineInstanceId, string status, int progress, string? errorMessage)
    {
        try
        {
            // 推送到订阅该任务状态的客户端
            var taskStatusGroup = $"task-status-{pipelineInstanceId}";
            await _hubContext.Clients.Group(taskStatusGroup).SendAsync("ReceiveTaskStatus", new
            {
                taskId,
                pipelineInstanceId,
                status,
                progress,
                errorMessage,
                timestamp = DateTime.UtcNow
            });

            // 同时推送到订阅整个流水线实例的客户端
            var pipelineGroup = $"pipeline-instance-{pipelineInstanceId}";
            await _hubContext.Clients.Group(pipelineGroup).SendAsync("ReceiveTaskStatus", new
            {
                taskId,
                pipelineInstanceId,
                status,
                progress,
                errorMessage,
                timestamp = DateTime.UtcNow
            });

            _logger.LogDebug("已推送任务状态到SignalR: TaskId={TaskId}, Status={Status}",
                taskId, status);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "推送任务状态到SignalR失败: TaskId={TaskId}", taskId);
        }
    }

    public async Task PushNodeStatusAsync(object nodeStatusData)
    {
        try
        {
            // 推送到订阅节点状态的所有客户端
            await _hubContext.Clients.Group("node-status").SendAsync("ReceiveNodeStatus", nodeStatusData);

            _logger.LogDebug("已推送节点状态到SignalR");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "推送节点状态到SignalR失败");
        }
    }
}
